const path = require('path');
const fs = require('fs');
const { getHeader, setHeader } = require('./helper')

module.exports = function (message, env) {
    if (message.request.status) {
        return message;
    }

    const authData = getHeader(message.request.headers, 'Authorization');
    // username: admin, password: 123
    // Basic base64(user:pass)
    if (authData) {
        const parseAuthData = authData.match(/basic\s*(\w+)/i);
        // console.log(parseAuthData); // 结果如下：
        // [
        //     'Basic YWRtaW46MTIz',
        //     'YWRtaW46MTIz',
        //     index: 0,
        //     input: 'Basic YWRtaW46MTIz',
        //     groups: undefined
        //   ]
        if (parseAuthData[1]) {
            const authPair = Buffer.from(parseAuthData[1], 'base64').toString().split(':');

            // 用户密码信息正确的时候
            if (authPair[0] === 'admin' && authPair[1] === '123') {
                const sessionID = 'session_' + new Date().getTime();

                const sessionPath = path.resolve(env.session, sessionID);

                fs.writeFileSync(sessionPath, authPair[0]);
                setHeader(message.response.headers, 'Set-Cookie', 'sessionid=' + sessionID + ';max-age=3600');
                return message;
            } else { // 用户密码信息不正确的时候
                message.response.status = 401;
                setHeader(message.response.headers, 'WWW-Authenticate', 'Basic realm="login"');
                return message;
            }
        }
    }
    const cookieData = getHeader(message.request.headers, 'Cookie');
    if (cookieData) {
        const parseCookieData = cookieData.match(/sessionid=(session_\d+)/i);
        if (parseCookieData && parseCookieData[1]) {
            const sessionPath = path.resolve(env.session, parseCookieData[1]);
            if (fs.existsSync(sessionPath)) {
                if (fs.readFileSync(sessionPath).toString() === 'admin') {
                    return message;
                }
            }
        }
    }

    message.response.status = 401;
    setHeader(message.response.headers, 'WWW-Authenticate', 'Basic realm="login"');
    return message;
}